<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button
                    size="small"
                    type="success"
                    @click="hAssignPer(row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="hDel(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :current-page="q.page"
                :page-sizes="[2, 3, 5, 8, 10]"
                :page-size="q.pagesize"
                layout="total, sizes, prev, pager, next,
              jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 新增角色弹层 -->
      <el-dialog
        :title="isEdit ? '编辑角色' : '新增角色'"
        :visible.sync="showDialog"
      >
        <el-form
          ref="roleFormRef"
          :model="roleForm"
          :rules="rulesForm"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="reset">取消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="hSubmit"
            >确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限弹层 -->
      <el-dialog :visible.sync="showDialogPer" title="分配权限">
        <assignPermission
          v-if="showDialogPer"
          :id="curId"
          @close="showDialogPer = false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getRolesList,
  addRolesList,
  updateRolesList,
  delRolesList
} from '@/api/setting'
import assignPermission from './assignPermission'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      curId: '',
      q: {
        page: 1, // 页码值
        pagesize: 2 // 每页显示的条数
      },
      list: [],
      total: 0,
      showDialog: false,
      showDialogPer: false,
      isEdit: false,
      roleForm: {
        name: '',
        description: ''
      },
      rulesForm: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],

        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.loadRolesList()
  },
  methods: {
    hAssignPer(id) {
      this.curId = id
      this.showDialogPer = true
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.q.page = 1
      this.q.pagesize = val
      this.loadRolesList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.q.page = val
      this.loadRolesList()
    },
    // 获取角色列表
    async loadRolesList() {
      try {
        const res = await getRolesList(this.q)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    async doAdd() {
      try {
        const res = await addRolesList(this.roleForm)
        console.log(res)
        this.total++
        const maxPage = Math.ceil(this.total / this.q.pagesize)
        this.q.page = maxPage
        this.loadRolesList()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    async doEdit() {
      try {
        await updateRolesList(this.roleForm)
        this.loadRolesList()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      this.$refs.roleFormRef.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hAdd() {
      this.isEdit = false
      this.showDialog = true
    },
    hEdit(data) {
      this.isEdit = true
      this.roleForm = { ...data }
      this.showDialog = true
    },
    hDel(id) {
      this.$confirm('确定删除该角色吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delRolesList(id)

          // 判断页面中是否只有一条数据,如果只有一条让当前页码值减一
          if (this.list.length === 1) {
            this.q.page--
            if (this.q.page <= 0) {
              this.q.page = 1
            }
          }
          this.loadRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    reset() {
      // 重置表单
      this.$refs.roleFormRef.resetFields()
      this.roleForm = {
        name: '',
        description: ''
      }
      this.showDialog = false
    }
  }
}
</script>
